const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const assessModel = require('../models/assess');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {orderId,customer,content,score} = req.body;
  const id = uuid.v1();
  const date=new Date();
  const assess = new assessModel({id,orderId,customer,content,date,score});
  assess.save().then(data=>{
    if(data){
      res.json(Message(200,'评价成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    assessModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

// router.put('/',(req,res,next)=>{
//   const {id}=req.query;
//   const {rating,reamrk}=req.body;
//   if(id){
//     assessModel.updateOne({id},{rating,reamrk}).then(data=>{
//       if(data.acknowledged&&data.modifiedCount!==0){
//         res.json(Message(200,'修改成功！'));
//       }else{
//         res.json(Message(400,'修改失败！'));
//       }
//     })
//   }else{
//     res.json(Message(400,'缺少参数id'));
//   }
// })

router.get('/',(req,res,next)=>{
  let {type}=req.query
  let {page=1,pageSize=5}=req.query;
  let queryObj={}
  switch(Number(type)){
    case 0: queryObj={};break;
    case 4: queryObj.$and=[{score: {$gte: 4}},{score: {$lte: 5}}];break;
    case 3: queryObj.$and=[{score: {$gte: 3}},{score: {$lt: 4}}];break;
    case 2: queryObj.$and=[{score: {$lte: 2}}];break;
  }
  assessModel.find(queryObj).count((err,count)=>{
    assessModel.find(queryObj)
      .limit(pageSize)
      .skip((page-1)*pageSize)
      .then(data=>{
        res.json(MessageList(200,'',data,page,pageSize,count));
    })
  })
})
module.exports = router